<?php

namespace Trawind\Extension\Helpers;

use Illuminate\Validation\Rule;
use Trawind\ConfigCenter\Helpers\ConfigHelper;
use Trawind\Extension\Models\Deploy\Language;

class LanguageHelper
{

    public static function rule()
    {
        return [
            'languages' => 'array',
            'languages.*.field' => [
                'string',
                Rule::requiredIf(!empty(request()->input('languages')))
            ],
            'languages.*.language' => [
                'string',
                Rule::in(array_keys(Language::LANGUAGE_TYPE_ENUM)),
                Rule::requiredIf(!empty(request()->input('languages')))
            ],
            'languages.*.content' => [
                'string',
                Rule::requiredIf(!empty(request()->input('languages')))
            ],
        ];
    }


    public static function createLanguages($model, array $languages)
    {
        if (!empty($languages)) {
            $maxId = Language::max('id');
            foreach ($languages as &$language) {
                $language['id'] = ++$maxId;
                unset($language);
            }
            $model->languages()->delete();
            $model->languages()->createMany($languages);
        }
    }


    public static function keyByField(array $data)
    {
        foreach ($data as &$item) {
            $item['languages'] = array_column($item['languages'] ?? [], null, 'field');
            unset($item);
        }

        return $data;
    }


    /**
     * @param  string|array  $relations
     * @return array
     */
    public static function withUseLanguage($relations = 'languages')
    {
        is_array($relations) or $relations = [$relations];

        $languageRelations = [];
        foreach ($relations as $relation) {
            $languageRelations[$relation] = function ($query) {
                $useLanguage = ConfigHelper::resolve('language', 'zh_CN');
                $query->where('language', $useLanguage);
            };
        }

        return $languageRelations;
    }


}